package com.dys.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @className: com.dys.typehandler.ListVarcharTypeHandler
 * @description: 实现List集合和varchar之间的转换
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/11/04 23:40
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListVarcharTypeHandler extends BaseTypeHandler<List<String>> {
    /**
     * 插入数据的时候要实现的数据转换是
     * List 转换为 字符串
     * String sql = "";
     * PreparedStatement ps = conn.createPreparedStatement(sql);
     * ps.setInt(1,14);
     * ps.setString(2,"aaa");
     * ps.setString(3,list.toString());
     * ps.setString(4,"湖南长沙");
     * ......
     * ps.executeUpdate();
     * ......
     *
     * @param ps        预编译语句
     * @param i         执行的SQL语句要插入参数的位置
     * @param parameter 要插入的位置的数据的List类型
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        System.out.println("setNonNullParameter......");
        // 处理数据，将List转换为特定格式的字符串
        StringBuffer sb = new StringBuffer();
        String msg = null;
        if (parameter != null) {
            for (String p : parameter) {
                sb.append(p).append(";");
            }
            msg = sb.toString();
            msg = msg.substring(0, msg.length() - 1);
        }
        // 给对应位置的占位符赋值
        ps.setString(i, msg);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String col = rs.getString(columnName);
        if (col != null) {
            return Arrays.asList(rs.getString(columnName).split(";"));
        }
        return null;
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return Arrays.asList(rs.getString(columnIndex).split(";"));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return Arrays.asList(cs.getString(columnIndex).split(";"));
    }
}
